package com.example;

import com.example.annotation.RequestParam;
import com.example.utils.AssertUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.Map;

public class ParameterDefinitionHandler {

    public static Object[] handlerParameter(Method method, HttpServletRequest request, HttpServletResponse response) {
        Parameter[] parameters = method.getParameters();
        if (parameters.length == 0) {
            return new Object[]{};
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        Object[] parameterValues = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            if (parameter.getType() == HttpServletRequest.class) {
                parameterValues[i] = request;
            } else if (parameter.getType() == HttpServletResponse.class) {
                parameterValues[i] = response;
            } else {
                RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
                String message = String.format("method %s param %s required", method.getName(), parameter.getName());
                AssertUtils.isTrue(requestParam != null, message);
                String paramName = "".equals(requestParam.value()) ? parameter.getName() : requestParam.value();
                String[] paramValues = parameterMap.get(paramName);
                Object paramValue;
                if(requestParam.required()){
                    AssertUtils.isTrue(paramValues != null && paramValues.length > 0,message);
                }
                if(paramValues != null && paramValues.length > 0){
                    paramValue = Arrays.toString(paramValues).replaceAll("\\[|\\]", "").replaceAll("\\s+", ",");
                }else{
                    paramValue = null;
                }
                parameterValues[i] = paramValue;
            }
        }
        return parameterValues;
    }
}
